package com.example.forestmanagement;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;
import java.io.IOException;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "RegisterActivity";
    private static final String BASE_URL = "http://8.130.186.54:3000";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    private EditText etEmail, etCode, etPassword, etConfirmPassword;
    private Button btnGetCode, btnRegister;
    private TextView tvLogin;
    private ImageButton btnBack;
    private OkHttpClient client;
    private CountDownTimer codeTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        
        client = new OkHttpClient();
        initViews();
        initListeners();
    }

    private void initViews() {
        etEmail = findViewById(R.id.et_email);
        etCode = findViewById(R.id.et_code);
        etPassword = findViewById(R.id.et_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        btnGetCode = findViewById(R.id.btn_get_code);
        btnRegister = findViewById(R.id.btn_register);
        tvLogin = findViewById(R.id.tv_login);
        btnBack = findViewById(R.id.btn_back);
    }

    private void initListeners() {
        btnGetCode.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
        tvLogin.setOnClickListener(this);
        btnBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_get_code) {
            requestVerificationCode();
        } else if (v.getId() == R.id.btn_register) {
            register();
        } else if (v.getId() == R.id.tv_login) {
            finish();
        } else if (v.getId() == R.id.btn_back) {
            finish();
        }
    }

    private void requestVerificationCode() {
        String email = etEmail.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            Toast.makeText(this, "请输入邮箱", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", email);
            String jsonStr = jsonObject.toString();
            
            String url = BASE_URL + "/api/mail/code";
            Log.d(TAG, "请求URL: " + url);
            Log.d(TAG, "请求体: " + jsonStr);

            RequestBody body = RequestBody.create(JSON, jsonStr);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "请求失败: " + e.getMessage());
                    runOnUiThread(() -> Toast.makeText(RegisterActivity.this, 
                            "获取验证码失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseData = response.body().string();
                    Log.d(TAG, "响应数据: " + responseData);
                    try {
                        JSONObject result = new JSONObject(responseData);
                        boolean success = result.getBoolean("success");
                        final String message = result.getString("message");
                        
                        runOnUiThread(() -> {
                            Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
                            if (success) {
                                startCodeTimer();
                            }
                        });
                    } catch (Exception e) {
                        Log.e(TAG, "解析响应失败: " + e.getMessage());
                        runOnUiThread(() -> Toast.makeText(RegisterActivity.this, 
                                "获取验证码失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "构建请求失败: " + e.getMessage());
            Toast.makeText(this, "获取验证码失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void startCodeTimer() {
        btnGetCode.setEnabled(false);
        if (codeTimer != null) {
            codeTimer.cancel();
        }
        
        codeTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                btnGetCode.setText(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                btnGetCode.setEnabled(true);
                btnGetCode.setText("获取验证码");
            }
        }.start();
    }

    private void register() {
        String email = etEmail.getText().toString().trim();
        String code = etCode.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();

        if (TextUtils.isEmpty(email)) {
            Toast.makeText(this, "请输入邮箱", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(confirmPassword)) {
            Toast.makeText(this, "请确认密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("account", email);
            jsonObject.put("password", password);
            jsonObject.put("code", code);
            String jsonStr = jsonObject.toString();
            
            String url = BASE_URL + "/api/user/reg";
            Log.d(TAG, "请求URL: " + url);
            Log.d(TAG, "请求体: " + jsonStr);

            RequestBody body = RequestBody.create(JSON, jsonStr);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "请求失败: " + e.getMessage());
                    runOnUiThread(() -> Toast.makeText(RegisterActivity.this, 
                            "注册失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseData = response.body().string();
                    Log.d(TAG, "响应数据: " + responseData);
                    try {
                        JSONObject result = new JSONObject(responseData);
                        boolean success = result.getBoolean("success");
                        
                        if (success) {
                            runOnUiThread(() -> {
                                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                                finish();
                            });
                        } else {
                            final String message = result.optString("message", "注册失败");
                            runOnUiThread(() -> Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show());
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "解析响应失败: " + e.getMessage());
                        runOnUiThread(() -> Toast.makeText(RegisterActivity.this, 
                                "注册失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "构建请求失败: " + e.getMessage());
            Toast.makeText(this, "注册失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (codeTimer != null) {
            codeTimer.cancel();
        }
    }
} 